package com.home.cop.sysinfo.service.impl;

import com.home.cop.enums.sysinfo.RegionLevelEnum;
import com.home.cop.sysinfo.mapper.RegionMapper;
import com.home.cop.sysinfo.model.Region;
import com.home.cop.sysinfo.service.RegionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class RegionServiceImpl implements RegionService {

    @Autowired
    private RegionMapper regionMapper;
    @Override
    public List<Region> list(String code) {
        if (StringUtils.isNotBlank(code)){
            code = code.trim();
        }else {
            code = null;
        }
        return regionMapper.list(code);
    }

    @Override
    public List<Region> regionTree() {
        List<Region> list = regionMapper.getAllRegions();
        //省
        List<Region> provList = new ArrayList<>();
        List<Region> cityList = new ArrayList<>();
        List<Region> countryList = new ArrayList<>();

        for (Region region:list){
            region.setChildren(new ArrayList<Region>());
            if (region.getRegionLevel()==RegionLevelEnum.PROVINCE.getCode()){
                provList.add(region);
            }else if (region.getRegionLevel()==RegionLevelEnum.CITY.getCode()){
                cityList.add(region);
            }else if (region.getRegionLevel()==RegionLevelEnum.COUNTRY.getCode()){
                countryList.add(region);
            }
        }
        Collections.sort(countryList);
        //组装市
        for (Region region:cityList){
            for (Region region1:countryList){
                if (region1.getParRegionId().equals(region.getRegionId())){
                    region.getChildren().add(region1);
                }
            }
        }
        Collections.sort(cityList);
        //组装省
        for (Region region:provList){
            for (Region region1:cityList){
                if (region1.getParRegionId().equals(region.getRegionId())){
                    region.getChildren().add(region1);
                }
            }
        }
        Collections.sort(provList);
        return provList;
    }
}
